package com.dialog.suotalib.utils;

import android.os.Environment;
import android.util.Log;

import com.dialog.suotalib.global.SuotaLibConfig;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

public class FileUtils {
    public static File write(String mk, String fileName, String content) {
        //1. 判断sd卡状态, 如果是挂载的状态才继续, 否则提示
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            File file = new File(SuotaLibConfig.Default.SDPATH + mk);
            if (!file.exists()) {
                file.mkdirs();//创建文件夹
            }
//            String filePath = SuotaLibConfig.Default.SDPATH + fileName;
//            RandomAccessFile randomAccessFile=new RandomAccessFile(filePath,"rw");
//            long fileLength=randomAccessFile.length();
//            randomAccessFile.seek(fileLength);
//            randomAccessFile.writeBytes(content);

            FileOutputStream fos = null;
            try {
//                FileWriter writer = new FileWriter(SuotaLibConfig.Default.SDPATH + SuotaLibConfig.getMkDir() + "/" + fileName,
                FileWriter writer = new FileWriter(SuotaLibConfig.Default.SDPATH + fileName+".txt",
                        true);
                Log.i("手势文件", SuotaLibConfig.Default.SDPATH  + fileName+".txt");
                writer.write(content);
                writer.close();
                //4. 写数据
                Log.i("生成手势", "success");
                return file;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            //5. 提示
        } else {
            Log.e("生成手势", "fail");

        }
        return null;
    }

    public static File delete() {
        //1. 判断sd卡状态, 如果是挂载的状态才继续, 否则提示
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            File file = new File(SuotaLibConfig.Default.SDPATH );
            if (!file.exists()) {
                file.mkdirs();//创建文件夹
            }
            File[] files = file.listFiles();
            if (files != null && files.length > 1) { // 确保文件数组不为空且至少有两个文件
                for (int i = 0; i < files.length - 1; i++) { // 遍历除最后一个外的所有文件
                    if (files[i].isFile()) { // 确保是文件而不是目录
                        Log.i(" 删除文件",files[i].getAbsolutePath());
                        files[i].delete(); // 删除文件
                    }
                }
            }
//            String filePath = SuotaLibConfig.Default.SDPATH + fileName;
//            RandomAccessFile randomAccessFile=new RandomAccessFile(filePath,"rw");
//            long fileLength=randomAccessFile.length();
//            randomAccessFile.seek(fileLength);
//            randomAccessFile.writeBytes(content);


            //5. 提示
        } else {
            Log.e("生成手势", "fail");

        }
        return null;
    }
}
